<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Visitorhistory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Config;
use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Redis;
use Log;
use App\Jobs\SendEmail;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class VisitorhistoryController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        date_default_timezone_set('asia/shanghai');
    }
    //获取所有数据
    public function all(Request $request)
    {   
        $input = $request->input();
        $isInvite = isset($input['isInvite']) ? $input['isInvite'] : 0;
        $list = DB::table('visitorHistory')
            ->leftJoin('employeeInfo','visitorHistory.invitedId','=','employeeInfo.id')
        ->where(function($query) use($input)
        { 
            if (!empty($input['realName'])) 
            {  
                $query->where('visitorHistory.realName', 'like', '%' . $input['realName'] . '%')
                    ->orwhere('visitorHistory.mobile', 'like', '%' . $input['realName'] . '%')
                    ->orwhere('visitorHistory.remarkName', 'like', '%' . $input['realName'] . '%')
                    ->orwhere('employeeInfo.name', 'like', '%' . $input['realName'] . '%');
            }
        })
        ->where(function($query) use($input) 
        {
            if (!empty($input['visitorTypeId'])) 
            {  
                $query->where('visitorHistory.visitorTypeId', '=', $input['visitorTypeId']);
            }  
        })
        ->where(function($query) use($input) 
        {
            if (!empty($input['visitTime'])) 
            {
                $query->whereBetween('visitorHistory.visitTime', [$input['visitTime'],$input['visitTime']+3600*24-1]);
            }  
        })
        ->where(function($query) use($input) 
        {
            if (!empty($input['planedTime'])) 
            {
                $query->whereBetween('visitorHistory.planedTime', [$input['planedTime'],$input['planedTime']+3600*24-1]);
            }  
        })
        ->where('visitorHistory.cmpId', '=', $input['cmpId'])
        ->where('visitorHistory.isInvite', '=', $isInvite)
        ->select('visitorHistory.id','visitorHistory.invitedId','visitorHistory.cmpId','visitorHistory.visitorTypeId','visitorHistory.realName','visitorHistory.mobile','visitorHistory.remarkName','visitorHistory.remarks','visitorHistory.remarks','visitorHistory.status','visitorHistory.planedTime','visitorHistory.visitTime','employeeInfo.name')
        ->orderBy('visitorHistory.visitTime','desc')
        ->get()->toArray();
        $page = isset($input['page']) ? $input['page'] : 1;
        if ($request->has('page')) 
        {
            $currentPage = $input['page'];
            $currentPage = $currentPage <= 0 ? 1 :$currentPage;
        } else 
        {
            $currentPage = 1;
        }
        $perPage = isset($input['perPage']) ? $input['perPage'] : 16;
        if (!count($list))
        {
             $data =  array('pageNum' =>1, 'count' =>0, 'item' => []);
            return $this->respond('get_ok', $data);
        }
        $item = array_slice($list, ($currentPage-1)*$perPage, $perPage);
        foreach($item as $key=>$val)
        {
//            $val->invitedId && $item2 = DB::table('employeeInfo')
//            ->select('name')->where('id',$val->invitedId)->first();
            $val->name = empty($val->invitedId) ? $val->remarkName : $val->name;
            if($isInvite == 1)
            {   
                if($val->planedTime && $val->planedTime > time() && !in_array($val->status,['1','2'])) 
                {
                    $item[$key]->status = '0';
                }
                if($val->planedTime && ($val->planedTime+600) <= time() && !in_array($val->status,['1','2'])) 
                {
                    $item[$key]->status = '3';
                }
            }
            $item[$key]->status = strval($item[$key]->status);
        }
        $count = count($list);
        $pageNum = ceil($count/$perPage);
        $data = array('pageNum' => $pageNum, 'count' => $count, 'item' => $item);
        return $this->respond('get_ok', $data);
    }
    //获取单个访客详情
    public function get($id)
    {
        $detail = DB::table('visitorHistory')->find($id);
       
        if (empty($detail)) 
        {
            return $this->respond('get_error');
        }
        $visitorTpe = DB::table('visitorType')->where(['cmpId'=>$detail->cmpId,'type'=>$detail->visitorTypeId])->first();
        $detail->typeId = $visitorTpe->id;
        $detail->deviceId && $item3 = DB::table('deviceInfo')
        ->select('deviceName')->where('id',$detail->deviceId)->first();
        $detail->deviceName = isset($item3) ? $item3->deviceName : '';
        if($detail->isInvite == 1)
        {
            if($detail->planedTime && $detail->planedTime > time() && !in_array($detail->status,['1','2']) ) 
            {
                $detail->status = '0';
            }
            if($detail->planedTime && ($detail->planedTime+600) <= time() && !in_array($detail->status,['1','2']) ) 
            {
                $detail->status = '3';
            }
            if($detail->status == '0')
            {
               $detail->cancel = '1';
            }
            if($detail->status == '3')
            {
               $detail->cancel = '1';
               $detail->again = '1';
            }
            if(in_array($detail->status,['1','2']))
            {
               $detail->again = '1';
            }
        }
        $detail->invitedId && $item2 = DB::table('employeeInfo')
        ->select('*')->where('id',$detail->invitedId)->first();
        $result['self'] = $detail;
        $result['inviteInfo'] = isset($item2) ? $item2 : ['name'=>$detail->remarkName];
        $othersInfo = DB::table('custom')
            ->join('visitorTypeSet','custom.typeSetId','=','visitorTypeSet.id')
            ->where(['custom.historyId'=>$id,'visitorTypeSet.isHidden'=>1])
            ->select('custom.typeName','custom.value')->get()->toArray();
        $visitorType = DB::table('visitorType')->where([['cmpId',$detail->cmpId],['type',$detail->visitorTypeId]])->first();
        $default = DB::table('visitorTypeSet')
            ->where([['cmpId',$detail->cmpId],['isHidden',1],['visitorTypeId',$visitorType->id]])
            ->whereNotIn('typeSign',[100,1])
            ->get();
        foreach($default as $k=>$v){
            if($v->typeSign == 2){
                $othersInfo[] =['typeName'=>'性别','value'=>$detail->sex];
            }else if($v->typeSign == 8){
                $othersInfo[] =['typeName'=>'公司','value'=>$detail->company];
            }else if($v->typeSign == 4){
                $othersInfo[] =['typeName'=>'邮箱','value'=>$detail->email];
            }else if($v->typeSign == 5){
                $othersInfo[] =['typeName'=>'同行人数','value'=>$detail->partnerNum];
            }
            else if($v->typeSign == 6){
                $othersInfo[] =['typeName'=>'身份证','value'=>$detail->idCard];
            }
            else if($v->typeSign == 7){
                $othersInfo[] =['typeName'=>'备注','value'=>$detail->remarks];
            }
        }
        if(empty($othersInfo)){
            $othersInfo = '';
        }
        $result['self']->others = $othersInfo;
        return $this->respond('get_ok', $result);
    }
    //增加单个访客记录
    public function add(Request $request)
    {   
        $input = $request->input();
        if(!isset($input['realName']) || !isset($input['mobile']) || !isset($input['cmpId']) || empty($input['visitorTypeId']) )
        {
            return $this->respond('empty_error');
        }
        $time = time();
        $data['realName'] = $input['realName'];
        $data['mobile'] = $input['mobile'];
        $data['cmpId'] = $input['cmpId'];
        $data['visitorTypeId'] = $input['visitorTypeId'];
        isset($input['remarks']) && $data['remarks'] = $input['remarks'];
        isset($input['sex']) && $data['sex'] = $input['sex'];
        isset($input['idCard']) && $data['idCard'] = $input['idCard'];
        isset($input['email']) && $data['email'] = $input['email'];
        isset($input['company']) && $data['company'] = $input['company'];
        isset($input['partnerNum']) && $data['partnerNum'] = $input['partnerNum'];
        isset($input['invitedId']) && $data['invitedId'] = $input['invitedId'];
        $data['photo'] = !empty($input['photo']) ? $input['photo'] : 'company/visitorDefault.png';
        $data['remarkName'] = empty($input['invitedId']) ? $input['remarkName'] : '';
        $input['isInvite'] = isset($input['isInvite']) ? $input['isInvite'] : 0;
        $data['visitTime'] = $time;
        $data['planedTime'] = !$input['isInvite'] ? 0 : $input['planedTime'];
        $data['status'] = !$input['isInvite'] ? '2' : '0';
        $data['isInvite'] = !$input['isInvite'] ? '0' : '1';
        $others = $request->input('others');
        //ipad端设备序列号
        if(isset($input['idfa']))
        {
            $device = DB::table('deviceInfo')
            ->select('id')->where('idfa',$input['idfa'])->first();
            if(empty($device))
            {
                $return = ['code'=>500,'msg'=>'设备序列号无效！'];
                return response()->json($return);
            }
            $time = time();
            $data['deviceId'] = $device->id;
        }
        $data['createdAt'] = $time;
        $data['updatedAt'] = $time;
        try{
            DB::beginTransaction();
            $id = DB::table('visitorHistory')->insertGetId($data);
            if(!empty($others) && $others !='[]'){
                foreach($others as $k=>$v){
                    DB::table('custom')->insert(['typeSetId'=>$v['id'],'historyId'=>$id,'typeName'=>$v['typeName'],'value'=>$v['value'],'createdAt'=>$time,'updatedAt'=>$time]);
                }
            }
             DB::commit();
        }catch(\Exception $e )
         {
             DB::rollback();
             return $this->respond('add_error');
            
         }
        if($id)
        {
            $messageConfig = DB::table('cmpInfo')->find($input['cmpId']);
            $data['cmp'] = $messageConfig->cmpName;
            isset($data['invitedId']) && $invitedr = DB::table('employeeInfo')->find($data['invitedId']);
           
            if($data['isInvite'] == '1' && !empty($invitedr) )
            {//新建邀约发送短信、邮件
               
                set_time_limit(0);
                try {
                
                    if($messageConfig->isMessageOn && !empty($data['mobile'])){
                        //拜访者短信

                        $this->sendSms(1, $input['cmpId'], $data, $invitedr);
                    }
                    if($messageConfig->isMessageOn && !empty($invitedr->mobile)){
                        //被访者短信

                        $this->sendSms(2, $input['cmpId'], $data, $invitedr);
                    }
                   
                    if($messageConfig->isMailOn && !empty($request->input('email'))){
                        //拜访者邮件
                       
                        $this->sendemail($input['cmpId'], $data, $invitedr,2);
                    }
                   
                    if($messageConfig->isMailOn && !empty($invitedr->email)){
                        //被访者邮件
                        $this->sendemail($input['cmpId'], $data, $invitedr,1);
                    }
                }catch (\Exception $e) {
                    $errorInfo = 'PC短信或邮件发送失败'.$e->getMessage();
                    Log::info($errorInfo);
                }
            }else if($data['isInvite'] == '0' && !empty($invitedr) )//访客登记
            {
                $messageConfig = DB::table('cmpInfo')->find($input['cmpId']);
                try {
                    set_time_limit(0);
                    if($messageConfig->isMessageOn && !empty($invitedr->mobile)){
                        //被访者短信
                        $this->sendSms(3, $input['cmpId'], $data, $invitedr);
                    }
                    if($messageConfig->isMailOn && !empty($invitedr->email)){
                        //被访者邮件
                        $this->sendemail($input['cmpId'], $data, $invitedr,5);
                    }
                }catch (\Exception $e) {
                    $errorInfo = 'APP短信或邮件发送失败'.$e->getMessage();
                    Log::info($errorInfo);
                }
            }
            if($data['isInvite'] == '0')//来自访客登记完返回便签信息
            {
                if(!empty($input['type']))  DB::table('visitorHistory')
                ->where('id',$input['id'])->update(['status'=>2]);
                $note = $this->getNoteInfo($input);
                return $this->respond('add_ok',['note'=>$note]);
            }
            return $this->respond('add_ok',['id'=>$id]);
        }
        return $this->respond('add_error');
    }
    //更新单个访客记录
    public function update(Request $request, $id)
    {   
        $input = $request->input();
        $model = new Visitorhistory();
        $data = $model->find($id);
        if (empty($data))
        {
            return $this->respond('get_error');
        }
//        if($input['status'] !=1){
//            $photoInfo = $this->upload($request);
//            if($photoInfo['code'] == 200){
//                $photo = $photoInfo['data'];
//            }else{
//                return response()->json($photoInfo);
//            }
//        }else{
//            $photo = $input['photo'];
//        }
        
        $data['cmpId'] = $data->cmpId;
        isset($input['realName']) && $data['realName'] = $input['realName'];
        isset($input['mobile']) && $data['mobile'] = $input['mobile'];
        isset($input['invitedId']) && $data['invitedId'] = $input['invitedId'];
        isset($input['visitorTypeId']) && $data['visitorTypeId'] = $input['visitorTypeId'];
        isset($input['remarks']) && $data['remarks'] = $input['remarks'];
        isset($input['sex']) && $data['sex'] = $input['sex'];
        isset($input['idCard']) && $data['idCard'] = $input['idCard'];
        isset($input['email']) && $data['email'] = $input['email'];
        isset($input['photo']) && $data['photo'] = !empty($input['photo']) ? $input['photo'] : 'company/visitorDefault.png';
        isset($input['company']) && $data['company'] = $input['company'];
        isset($input['name']) && $data['name'] = $input['name'];
        isset($input['status']) && $data['status'] = $input['status'];
        $others = $request->input('others');
        $time = time();
        try{
            DB::beginTransaction();
            $status = $data->save();
            if(!empty($others) && $others != '[]'){
                DB::table('custom')->where('historyId',$id)->delete();
                foreach($others as $k=>$v){
                    DB::table('custom')->insert(['typeSetId'=>$v['id'],'historyId'=>$id,'typeName'=>$v['typeName'],'value'=>$v['value'],'createdAt'=>$time,'updatedAt'=>$time]);
                }
            }
            DB::commit();
        }catch(\Exception $e )
        {
            DB::rollback();
            return $this->respond('update_error');
        }
        if($status)
        {   
            //取消邀请发送短信\邮件
            $messageConfig = DB::table('cmpInfo')->find($data['cmpId']);
            $data['cmp'] = $messageConfig->cmpName;
            $invitedr = DB::table('employeeInfo')->find($data['invitedId']);
            if($data['status'] == '1' && !empty($invitedr) )
            {
                set_time_limit(0);
                try {
                if($messageConfig->isMessageOn && !empty($data['mobile'])){
                    $this->sendSms(4, $data->cmpId, $data->toArray(), $invitedr);
                }
                if($messageConfig->isMessageOn && !empty($invitedr->mobile)){
                    $this->sendSms(5, $data->cmpId, $data->toArray(), $invitedr);
                }
                if($messageConfig->isMailOn && !empty($data['email'])){
                    //拜访者邮件
                    $this->sendemail($data->cmpId, $data, $invitedr,3);
                }
                if($messageConfig->isMailOn && !empty($invitedr->email)){
                    //被访者邮件
                    $this->sendemail($data->cmpId, $data, $invitedr,4);
                }
                }catch (\Exception $e) {
                    $errorInfo = 'PC取消邀约短信或邮件发送失败'.$e->getMessage();
                    Log::info($errorInfo);
                }
            }
            
            return $this->respond('update_ok',['id'=>$id]);
        }
        return $this->respond('update_error');
    }
    //被访问人列表
    public function employeeInfoList(Request $request)
    {   
        $input = $request->input();
        $page = $this->page($request);
        $all = DB::table('employeeInfo')
        ->leftJoin('department','employeeInfo.deptId','department.id')
        ->select('employeeInfo.id','employeeInfo.name','department.name as departName')
        ->where('employeeInfo.cmpId',$input['cmpId'])
        ->where('employeeInfo.status',0)
        ->where(function($query) use($input) 
        {
            if (!empty($input['name'])) 
            {  
                $query->where('employeeInfo.name', 'like', '%' . $input['name'] . '%');
            }
        })
        ->skip($page['skip'])->take($page['take'])->get();
        if(!count($all))
        {
            return $this->respond('get_error');
        }
        return $this->respond('get_ok', ['list'=>$all]);
    }
    //今日访客数量
    public function todayVisitors($id)
    {   
        $start = strtotime(date('Y-m-d'));
        $end = $start+3600*24-1;
        $count = DB::table('visitorHistory') 
        ->where('visitorHistory.cmpId', '=', $id)
        ->where('visitorHistory.isInvite', '=', '0')
        ->whereBetween('visitorHistory.visitTime', [$start,$end])
        ->count();
        $res['count'] = $count;
        return $this->respond('get_ok', $res);
    }
    //最近一次被邀约或者以前来过
    public function lastRecord(Request $request)
    {
        $input = $request->input();
        $order = !$input['type'] ? 'asc' : 'desc';
        $orderBy = !$input['type'] ? 'visitorHistory.planedTime' : 'visitorHistory.visitTime';
        $first = DB::table('visitorHistory')
        ->where('visitorHistory.mobile', '=', $input['mobile'])
        ->where('visitorHistory.cmpId', '=', $input['cmpId'])
        ->where(function($query) use($input) 
        { 
            if ($input['type'] == 0) //我有预约
            {   
                $query->where('visitorHistory.status', '=', '0');
                $query->where('visitorHistory.isInvite', '=', '1');
                $query->where('visitorHistory.planedTime', '>=', time());
            }
            if ($input['type'] == 1) //以前来过
            {  
                $query->whereNotIn('visitorHistory.status', ['0']);
                $query->where('visitorHistory.isInvite', '=', '0');
            } 
        })
        ->orderBy($orderBy,$order)
        ->first();
        if(empty($first))
        {
            return response()->json(['code'=>400,'msg'=>'未找到您的记录','data'=>'']);
        }
        //获取被访人姓名
        $first->invitedId && $item2 = DB::table('employeeInfo')
        ->select('name')->where('id',$first->invitedId)->first();
        $first->name = isset($item2) ? $item2->name : $first->remarkName;
        //获取设备名
        $first->deviceId && $item3 = DB::table('deviceInfo')
        ->select('deviceName')->where('id',$first->deviceId)->first();
        $first->deviceName = isset($item3) ? $item3->deviceName : '';
        
        $vositorInfo = DB::table('visitorType')
        ->join('visitorTypeSet','visitorType.id','visitorTypeSet.visitorTypeId')
        ->where('visitorType.type',$first->visitorTypeId)
        ->where('visitorType.cmpId',$input['cmpId'])
        ->where('visitorTypeSet.typeName','拍照')->first();
        $first->isPhoto = isset($vositorInfo) && $vositorInfo->isHidden ? '1' : '0';
        $othersInfo = DB::table('custom')
            ->join('visitorTypeSet','custom.typeSetId','=','visitorTypeSet.id')
            ->where(['custom.historyId'=>$first->id,'visitorTypeSet.isHidden'=>1])
            ->select('custom.typeSetId as id','custom.typeName','custom.value')->get();
        if(empty($othersInfo->toArray())){
            $othersInfo = '';
        }
        $first->others = $othersInfo;
        return $this->respond('get_ok', $first);
    }
    public function export(Request $request)
    {
        $input = $request->input();
        $isInvite = isset($input['isInvite']) ? strval($input['isInvite']) : '0';
        $list = DB::table('visitorHistory')
        ->where('visitorHistory.cmpId', '=', $input['cmpId'])
        ->where('visitorHistory.isInvite', '=', $isInvite)
        ->leftJoin('employeeInfo','visitorHistory.invitedId','employeeInfo.id')
        ->leftJoin('deviceInfo','visitorHistory.deviceId','deviceInfo.id')
        ->where(function($query) use($input)
        { 
            if (!empty($input['realName'])) 
            {  
                $query->where('visitorHistory.realName', 'like', '%' . $input['realName'] . '%')->orwhere('visitorHistory.mobile', 'like', '%' . $input['realName'] . '%');
            }
        })
        ->where(function($query) use($input) 
        {
            if (!empty($input['visitorTypeId'])) 
            {  
                $query->where('visitorHistory.visitorTypeId', '=', $input['visitorTypeId']);
            } 
        })
        ->where(function($query) use($input) 
        {
            if (!empty($input['visitTime'])) 
            {
                $query->whereBetween('visitorHistory.visitTime', [$input['visitTime'],$input['visitTime']+3600*24-1]);
            }  
        })
        ->where(function($query) use($input) 
        {
            if (!empty($input['planedTime'])) 
            {
                $query->whereBetween('visitorHistory.planedTime', [$input['planedTime'],$input['planedTime']+3600*24-1]);
            }  
        })
        ->select('visitorHistory.*','employeeInfo.name as employeeInfoName','employeeInfo.mobile as employeeInfoMobile','employeeInfo.email as employeeInfoEmail','employeeInfo.remarks as employeeInfoRemarks','deviceInfo.deviceName')
        ->orderBy('visitorHistory.visitTime','desc')
        ->get()->toArray();
        if (!count($list))
        {   
            return $this->respond('get_error');
        }
        $cellData = [];
        $i = 1;
        if($isInvite == '0')
        {
            $cellData = [['访客姓名','访客电话','访客邮箱','来访人备注','来访类型','时间','被访人','被访人电话','被访人邮箱','被访人备注','设备名称']];
            $title = '访客记录_'.$this->msectime();
        }else
        {
            $cellData = [['被邀约人','电话','邀约类型','邮箱','公司','邀约时间','被访人','访问状态']];
            $title = '邀请访客记录_'.$this->msectime();
        }
        foreach($list as $key=>$val)
        {
            switch ($val->visitorTypeId) 
            {
                case '1':
                    $typeName = '面试';
                    break;
                case '2':
                    $typeName = '商务';
                    break;
                case '3':
                    $typeName = '亲友';
                    break;
                case '4':
                    $typeName = '其他';
                    break;
                default:
                    # code...
                    break;
            }
            $inviteName = $val->employeeInfoName  ? $val->employeeInfoName : $val->remarkName;
            if($isInvite == '0')
            {   
                $cellData[$i] = [$val->realName,$val->mobile,$val->email,$val->remarks,$typeName,date('Y-m-d H:i:s',$val->visitTime),$inviteName,$val->employeeInfoMobile,$val->employeeInfoEmail,$val->employeeInfoRemarks,$val->deviceName];
                $i++;
            }else{
                $status = $val->status;
                if($val->planedTime && $val->planedTime > time() && !in_array($val->status,['1','2']) ) 
                {
                    $status = 0;//待到访
                }
                if($val->planedTime && ($val->planedTime+600) <= time() && !in_array($val->status,['1','2']) ) 
                {
                    $status = 3;//未到访
                }
                if($status == 0) $tit = '待到访';
                if($status == 1) $tit = '已取消';
                if($status == 2) $tit = '已到访';
                if($status == 3) $tit = '未到访';
                $cellData[$i] = [$val->realName,$val->mobile,$typeName,$val->email,$val->company,date('Y-m-d H:i:s',$val->planedTime),$inviteName,$tit];
                $i++;
            }
        }
        Excel::create($title,function($excel) use ($cellData)
        {
            $excel->sheet('Sheet', function($sheet) use ($cellData)
            {
                $sheet->rows($cellData);
            });
        })->store('xls','uploads/excel');
        $path['filepath'] = '/uploads/excel/'.$title.'.xls';
        return $this->respond('get_ok', $path);
    }
    //生成当前微妙时间戳
    public function msectime() 
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    //发送邮件
    public function sendemail($cmpId, $vistor, $invitedr,$type)
    {
       
        $vistorTo = $vistor['email'];//访客邮箱
        $inviteTo = $invitedr->email;//被访人邮箱
        $vistorSubject = "来访通知";//被访人
        $vistor_arr=['面试','商务','亲友','其他'];
        $compnay = $vistor['cmp'];//公司名称
        $inviteName = $invitedr->name;//被访人姓名
        $visitorName = $vistor['realName'];//访客姓名
        $date= date('Y年m月d日 H:i',$vistor['planedTime']);//时间
        $purpose = $vistor_arr[$vistor['visitorTypeId']-1];
        $vistorPhone = $vistor['mobile'];//访客手机号
        $invitePhone = $invitedr->mobile;//被访人手机号
        $vistorType = $vistor['visitorTypeId'];
        switch($type){
//            新建邀约被访人
            case 1:
              
                $to = $inviteTo;
                $data['user'] = $inviteName;
                $data['name'] = $visitorName;
                $data['data'] = $date;
                $data['phone'] = $vistorPhone;
                $subject = $vistorSubject;
                
                if($vistorType == 1){
                    //面试
                    $data['purpose'] = '面试';
                    $view = 'emails.newinvite1';
                   
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 2){
                    //商务
                    $data['company'] = $compnay;
                    $view = 'emails.newinvite2';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 3){
                    //亲友
                    $data['company'] = $compnay;
                    $view = 'emails.newinvite3';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 4){
                    //其他
                    $data['company'] = $compnay;
                    $view = 'emails.newinvite4';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
            break;
            case '2':
//                新建邀约-访客
                $to = $vistorTo;
                $data['user'] = $visitorName;
                $data['name'] = $inviteName;
                $data['data'] = $date;
                $data['company'] = $compnay;
                $data['phone'] =  $invitePhone;
                $subject = '邀约通知';
                if($vistorType == 1){
                    //面试
                    $data['purpose'] = '面试';
                    $view = 'emails.newvistor1';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 2){
                    //商务
                    $view = 'emails.newvistor2';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 3){
                    //亲友
                    $view = 'emails.newvistor3';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 4){
                    //其他
                    $view = 'emails.newvistor4';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
            break;
            case '3':
//                取消邀约被访人
                $to = $inviteTo;
                $data['user'] = $inviteName;
                $data['name'] = $visitorName;
                $data['data'] = $date;
                $subject = '邀约取消通知';
                if($vistorType == 1){
                    //面试
                    $data['purpose'] = '面试';
                    $view = 'emails.cancelinvite1';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 2){
                    //商务
                    $view = 'emails.cancelinvite2';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 3){
                    //亲友
                    $view = 'emails.cancelinvite3';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 4){
                    //其他
                    $view = 'emails.cancelinvite4';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
            break;
            case '4':
                //取消邀约访客
                $to = $vistorTo;
                $data['user'] = $visitorName;
                $data['name'] = $inviteName;
                $data['data'] = $date;
                $data['company'] = $compnay;
                $data['phone'] =  $invitePhone;
                $subject = '邀约取消通知';
                if($vistorType == 1){
                    //面试
                    $data['purpose'] = '面试';
                    $view = 'emails.cancelvistor1';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 2){
                    //商务
                    $view = 'emails.cancelvistor2';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 3){
                    //亲友
                    $view = 'emails.cancelvistor3';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                if($vistorType == 4){
                    //其他
                    $view = 'emails.cancelvistor4';
                    dispatch(new SendEmail($view,$data,$to,$subject));
//                    Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                        $message->to($to,'我')->subject($subject);
//                    });
                }
                break;
            case '5':
                $to = $inviteTo;
                $data['user'] = $inviteName;
                $data['name'] = $visitorName;
                $data['phone'] =  $vistorPhone;
                $subject = '来访通知';
                $view = 'emails.notice';
                $data['purpose'] = $purpose;
                dispatch(new SendEmail($view,$data,$to,$subject));
//                Mail::send($view, ['data'=>$data], function ($message) use ($to, $subject) {
//                    $message->to($to,'我')->subject($subject);
//                });
                break;
            default :
                return  response()->json(['code'=>400,'msg'=>'邮件发送失败']);
            break;
        }
        $key = 'company_id_'.$cmpId.'_count';
        !Redis::exists($key) ? Redis::set($key,1) : Redis::incr($key);
        return  response()->json(['code'=>200,'msg'=>'邮件发送成功']);
    }
    //发送短信
    public function sendSms($type, $cmpId, $vistor, $invitedr)
    {
        $inviteType = $vistor['visitorTypeId'];
        $cmpInfo = DB::table('cmpInfo')->where('id',$cmpId)->first();
        $company = $cmpInfo->cmpName;//公司名称
        $config = Config::get('info.message_config');
        $easySms = new EasySms($config);
        $visitorMobile = $vistor['mobile'];//访客手机
        $vistorName = $vistor['realName'];//访客姓名
        $inviteName = $invitedr->name;//被访者姓名
        $inviteMobile = $invitedr->mobile;//被访者手机号
        $data = date('Y年m月d日 H:i',$vistor['planedTime']);
        if($type == '1')    //新建邀约时,向访客发送短信
        {
            switch($inviteType){
                //面试
                case '1':
                        $result = $easySms->send($visitorMobile, [
                            'content' => '尊敬的${visitor}， ${interviewee}邀请您于${data}来${company}参加${purpose}，请您按时参加，${cmp}期待您的到来。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                            'template' => 'SMS_134314137',
                            'data' => [
                                'visitor' => ' '.$vistorName.' ',
                                'interviewee' => ' '.$inviteName.' ',
                                'data' => $data,
                                'purpose' => '( 面-试 )',
                                'company' => '('.$company.')',
                                'cmp'=>'('.$company.')',
                                'interviewees' => ' '.$inviteName.' ',
                                'phone'=>$inviteMobile,
                            ],
                        ]);
                    break;
                //商务
                case '2':
                    $result = $easySms->send($visitorMobile, [
                        'content' => '尊敬的${visitor}，  ${interviewee}邀请您于${data}来${company}访问，请您及时确认，${cmp}期待您的光临。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                        'template' => 'SMS_134324139',
                        'data' => [
                            'visitor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'data' => $data,
                            'company' => '('.$company.')',
                            'cmp'=>'('.$company.')',
                            'interviewees' => " ".$inviteName." ",
                            'phone'=>$inviteMobile,
                        ],
                    ]);
                    break;
                //亲友
                case  '3':
                    $result = $easySms->send($visitorMobile, [
                        'content' => '尊敬的${visitor}， 您的亲友${interviewee}邀请您于${data}来${company}探访，请您及时确认，${cmp}期待您的光临。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                        'template' => 'SMS_134319164',
                        'data' => [
                            'visitor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'data' => $data,
                            'company' => '('.$company.')',
                            'cmp'=>'('.$company.')',
                            'interviewees' => " ".$inviteName." ",
                            'phone'=>$inviteMobile,
                        ],
                    ]);
                    break;
                //其他
                case '4':
                    $result = $easySms->send($visitorMobile, [
                        'content' => '尊敬的${visitor}，  ${interviewee}邀请您于${data}来${company}访问，请您及时确认，${cmp}期待您的光临。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                        'template' => 'SMS_134319169',
                        'data' => [
                            'visitor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'data' => $data,
                            'company' => '('.$company.')',
                            'cmp'=>'('.$company.')',
                            'interviewees' => " ".$inviteName." ",
                            'phone'=>$inviteMobile,
                        ],
                    ]);
                    break;
            }
        }else if($type == '2')//新建邀约时,向被访问者发送短息
        {
            switch($inviteType){
                //面试
                case '1':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，访客管理系统已邀约访客${visitor}于${data}来贵公司参加${purpose}，联系电话：${phone}，请您及时确认并安排时间接待。',
                        'template' => 'SMS_134329275',
                        'data' => [
                            'data' => $data,
                            'purpose' =>'( 面-试 )',
                            'visitor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'phone'=>$visitorMobile,
                        ],
                    ]);
                    break;
                case '2':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，访客管理系统已邀约访客${visitor}于${data}来${company}访问，联系电话：${phone}，请您及时确认并安排时间接待',
                        'template' => 'SMS_134329284',
                        'data' => [
                            'data' => $data,
                            'visitor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'company' => '('.$company.')',
                            'phone'=>$visitorMobile,
                        ],
                    ]);
                    break;
                case  '3':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，访客管理系统已邀约您的亲友${visitor}于${data}来${company}探访，联系电话：${phone}，请您及时确认并安排时间接待。',
                        'template' => 'SMS_134324144',
                        'data' => [
                            'data' => $data,
                            'visitor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'company' => '('.$company.')',
                            'phone'=>$visitorMobile,
                        ],
                    ]);
                    break;
                case '4':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，访客管理系统已邀约访客${visitor}于${data}来${company}访问，联系电话：${phone}，请您及时确认并安排时间接待。',
                        'template' => 'SMS_134324153',
                        'data' => [
                            'data' => $data,
                            'visitor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'company' => '('.$company.')',
                            'phone'=>$visitorMobile,
                        ],
                    ]);
                    break;
            }
          
        }else if($type == '3')//访问者被邀约时来访,向被访者发送短信
        {
            $vistor_arr=['面-试','商务','亲友','其他'];
            $purpose = $vistor_arr[$vistor['visitorTypeId']-1];
            $result = $easySms->send($inviteMobile, [
                'content' => '尊敬的${interviewee}，您的访客${visitor}已到达贵单位，来访类别${purpose}，联系电话：${phone}，请及时联系相关人员予以确认。',
                'template' => 'SMS_135042022',
                'data' => [
                    'purpose' =>'( '.$purpose.' )',
                    'visitor' => " ".$vistorName." ",
                    'interviewee' => " ".$inviteName." ",
                    'phone'=>$visitorMobile,
                ],
            ]);
        }else if($type == '4')//取消邀约时,向访客发送短信
        {   
            switch($inviteType){
                //面试
                case '1':
                    $result = $easySms->send($visitorMobile, [
                        'content' => '尊敬的${vistor}，您原定于${date}去${company}的${purpose}邀请已被取消。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                        'template' => 'SMS_135030518',
                        'data' => [
                            'vistor' => " ".$vistorName." ",
                            'purpose' => '( 面-试 )',
                            'company' => '('.$company.')',
                            'date' => $data,
                            'interviewees' => " ".$inviteName." ",
                            'phone'=>$inviteMobile,
                        ],
                    ]);
                    break;
                //商务
                case '2':
                    $result = $easySms->send($visitorMobile, [
                        'content' => '尊敬的${vistor}，您原定于${date}去${company}的访问邀请已被取消。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                        'template' => 'SMS_134324158',
                        'data' => [
                            'vistor' => " ".$vistorName." ",
                            'date' => $data,
                            'company' => '('.$company.')',
                            'interviewees' => " ".$inviteName." ",
                            'phone'=>$inviteMobile,
                        ],
                    ]);
                    break;
                //亲友
                case  '3':
                    $result = $easySms->send($visitorMobile, [
                        'content' => '尊敬的${vistor}，您原定于${date}去${company}的探访邀请已被取消。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                        'template' => 'SMS_135031511',
                        'data' => [
                            'company' => '('.$company.')',
                            'date' => $data,
                            'vistor' => " ".$vistorName." ",
                            'interviewees' => " ".$inviteName." ",
                            'phone'=>$inviteMobile,
                        ],
                    ]);
                    break;
                //其他
                case '4':
                    $result = $easySms->send($visitorMobile, [
                        'content' => '尊敬的${vistor}，您原定于${date}去${company}的访问邀请已被取消。如有疑问，请联系${interviewees}，联系电话：${phone}。',
                        'template' => 'SMS_135036483',
                        'data' => [
                            'company' => '('.$company.')',
                            'date' => $data,
                            'vistor' => " ".$vistorName." ",
                            'interviewees' => " ".$inviteName." ",
                            'phone'=>$inviteMobile,
                        ],
                    ]);
                    break;
            }
        }else if($type == '5')//取消邀约时,向被访问者发送短息
        {   
            switch($inviteType){
                //面试
                case '1':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，您的访客${vistor}原定于${date}的${purpose}已取消，如有疑问，请您联系访客管理系统管理员。',
                        'template' => 'SMS_135031751',
                        'data' => [
                            'vistor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'date' => $data,
                            'purpose' => '( 面-试 )',
                        ],
                    ]);
                    break;
                case '2':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，您的访客${vistor}原定于${date}的访问已取消，如有疑问，请您联系访客管理系统管理员。',
                        'template' => 'SMS_135026280',
                        'data' => [
                            'vistor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'date' => $data,
                        ],
                    ]);
                    break;
                case  '3':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，您的亲友${vistor}原定于${date}的探访已取消，如有疑问，请您联系访客管理系统管理员。',
                        'template' => 'SMS_135031080',
                        'data' => [
                            'vistor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'date' => $data,
                        ],
                    ]);
                    break;
                case '4':
                    $result = $easySms->send($inviteMobile, [
                        'content' => '尊敬的${interviewee}，您的访客${vistor}原定于${date}的访问已取消，如有疑问，请您联系访客管理系统管理员。',
                        'template' => 'SMS_135026275',
                        'data' => [
                            'vistor' => " ".$vistorName." ",
                            'interviewee' => " ".$inviteName." ",
                            'date' => $data,
                        ],
                    ]);
                    break;
            }
        }
        if($result['aliyun']['status']=='success'){
            $key = 'company_id_'.$cmpId.'_count';
            !Redis::exists($key) ? Redis::set($key,1) : Redis::incr($key);
//            return  response()->json(['code'=>200,'msg'=>'短信发送成功']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'短信发送失败']);
        }
    }
    //获取便签信息
    public function getNoteInfo($input)
    {
        $visitorInfo = DB::table('visitorInfo')
        ->where('type',$input['visitorTypeId'])
        ->where('cmpId',$input['cmpId'])->get();
        $note = array();
        $note['realName'] = $input['realName'];
        $note['mobile'] = $input['mobile'];
        foreach($visitorInfo as $key=>$val)
        {  
            if($val->typeName == '性别' && $val->isHidden){
                isset($input['sex']) && $note['sex'] = $input['sex'];
            }else if($val->typeName == '邮箱' && $val->isHidden){
                isset($input['email']) && $note['email'] = $input['email'];
            }else if($val->typeName == '身份证' && $val->isHidden){
                isset($input['idCard']) && $note['idCard'] = $input['idCard'];
            }else if($val->typeName == '备注' && $val->isHidden){
                isset($input['remarks']) && $note['remarks'] = $input['remarks'];
            }else if($val->typeName == '公司' && $val->isHidden){
                isset($input['company']) && $note['company'] = $input['company'];
            }else if($val->typeName == '同行人数' && $val->isHidden){
                isset($input['partnerNum']) && $note['partnerNum'] = $input['partnerNum'];
            }
        }
        $cmpInfo = DB::table('cmpInfo')->where('id',$input['cmpId'])->first();
        $note['noteSign'] = $cmpInfo->momeType ?? 1;
        $wifi = DB::table('cmpWifi')
        ->where('cmpId',$input['cmpId'])->first();
        $note['userName'] = !empty($wifi) ? $wifi->userName : '';
        $note['passWord'] = !empty($wifi) ? $wifi->passWord : '';
        !empty($input['invitedId']) && $item = DB::table('employeeInfo')->select('name')->where('id',$input['invitedId'])->first();
        $note['inviteName'] = isset($item) ? $item->name : $input['remarkName'];
        return $note;
    }
    //上传图片
    public function upload(Request $request)
    {
        if($request->input('photo' == '')){
            $return = ['code'=>500,'msg'=>'上传文件为空或无效','data'=>'company/visitorDefault.png'];
            return $return;
        }
        $file = $request->file('photo');
        if (!$request->hasFile('photo')) {
            $return = ['code'=>500,'msg'=>'上传文件为空或无效','data'=>[]];
            return $return;
        }
        if (!$request->file('photo')->isValid()){
            $return = ['code'=>500,'msg'=>$file->getErrorMessage(),'data'=>[]];
            return $return;
        }
        if(!in_array($file->getClientOriginalExtension(),['png','jpg','jpeg'])){
            $return = ['code'=>500,'msg'=>'图片格式不允许','data'=>[]];
            return  $return;
        }
        if($file->getClientSize() > $file->getMaxFilesize()){
            $return = ['code'=>500,'msg'=>'图片不允许超过2M','data'=>[]];
            return $return;
        }
        if (!empty($file)) {
            $newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
            $savePath = 'uploads/' . date('Ym', time());
            $request->file('photo')->move($savePath, $newFileName);
            
            $name = $savePath . '/' . $newFileName;
            $return = ['code'=>200,'msg'=>'上传文件成功','data'=>$name];
            return $return;
        }
    }
//    public function email(){
//        dispatch(newExampleJob('WJB'));
//    }
}
